import store from '../store'

export default (params) => {
  var baseUrl = process.env.VUE_APP_BASE_URL
  let token = uni.getStorageSync('token')

  return new Promise((resolve, reject) => {
    uni.request({
      ...params,
      url: `${baseUrl}${params.url}`,
      header: params.header || {
        "content-type": "application/json;charset=UTF-8",
        'x-token': token
      },
      success: (res) => {
        let data = res.data || {};
        if (data.code === 200) {
          resolve(data.data)
        } else if (data.code === 401) {
          uni.removeStorage("token");
          let page = getCurrentPages().pop();
          if (page.route != "pages/index/index") {
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }
        } else {
          reject(data)
        }
      },
      fail: (error) => {
        console.log(error)
        reject(error)
      }
    })
  })
}

// 附件下载
export function downloadFile(params) {
  var baseUrl = process.env.VUE_APP_BASE_URL
  let token = uni.getStorageSync('token')

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}${params.url}`,
      data: params.data,
      method: 'POST',
      header: params.header || {
        "content-type": "application/json;charset=UTF-8",
        'x-token': token
      },
      responseType: 'arraybuffer',
      success: (res) => {
        try {
          // 如果result不报错，说明后台返回的是json对象，则弹框提示，否则说明返回的是文件流，进入catch，下载文件
          let buffer = res.data;
          let dataview = new DataView(buffer);
          let ints = new Uint8Array(buffer.byteLength);
          let str = '';
          for (let i = 0; i < ints.length; i++) {
            str += String.fromCharCode(dataview.getUint8(i));
          }
          let result = JSON.parse(str);
          if (result.msg) {
            reject(result.msg);
          }
        } catch (err) {
          console.log(err)
          resolve(res.data)
        }
      },
      fail: (error) => {
        console.log(error)
        reject(error)
      }
    })
  })
}